import axios from 'axios'
import router from '@/router'
import {  Loading, Notification } from 'element-ui'
 // vant element axios
let loading

const http = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    //     [{"username":"jx"},{"username":"cc"}]
    //   "?username=jx&password=123456"
    //   "<xml><username>jx</username><password>123456</password></xml>"
    // 注意 设置这个  就代表该axios只能发送json了.不能发送form结构了  比如 ?username=jx&password=123456
    'Content-Type': 'application/json; charset=utf-8'
  }
})

function startLoading () {
  loading = Loading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
function endLoading () {
  loading.close()
}

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  if (localStorage.getItem('token') != null) {
      config.headers['token'] = localStorage.getItem('token') // 请求头带上token
  }
  startLoading()
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  endLoading()
  if (response.headers.token) {
    localStorage.setItem("token", response.headers.token)
    location.reload()
  }
  if (response.data.code === 401) {
    //debugger
    Notification.error({ title: '错误', message: '登录已失效请重新登录', duration: 2500 })
    localStorage.removeItem('token')
    router.push('/index')
  }
  return response
}, error => {
  return Promise.reject(error)
})
export default http
